package com.ruoyi.business.service.impl;

import java.util.*;

import cn.hutool.core.convert.Convert;
import com.ruoyi.business.domain.vo.MsgList;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.BusRepairMapper;
import com.ruoyi.business.domain.BusRepair;
import com.ruoyi.business.service.IBusRepairService;
import javax.annotation.Resource;

/**
 * 维修任务Service业务层处理
 * 
 * @author wf
 * @date 2024-07-18
 */
@Service
public class BusRepairServiceImpl implements IBusRepairService 
{
    @Resource
    private BusRepairMapper busRepairMapper;

    @Autowired
    private SysPermissionService permissionService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询维修任务
     * 
     * @param id 维修任务主键
     * @return 维修任务
     */
    @Override
    public BusRepair selectBusRepairById(Long id)
    {
        return busRepairMapper.selectBusRepairById(id);
    }

    /**
     * 查询维修任务列表
     * 
     * @param busRepair 维修任务
     * @return 维修任务
     */
    @Override
    public List<BusRepair> selectBusRepairList(BusRepair busRepair)
    {
        return busRepairMapper.selectBusRepairList(busRepair);
    }

    /**
     * 新增维修任务
     * 
     * @param busRepair 维修任务
     * @return 结果
     */
    @Override
    public int insertBusRepair(BusRepair busRepair)
    {
        busRepair.setCreateUser(SecurityUtils.getUserId());
        busRepair.setCreateBy(SecurityUtils.getUsername());
        busRepair.setCreateTime(DateUtils.getNowDate());
        busRepair.setUpdateUser(SecurityUtils.getUserId());
        busRepair.setUpdateBy(SecurityUtils.getUsername());
        busRepair.setUpdateTime(DateUtils.getNowDate());
        return busRepairMapper.insertBusRepair(busRepair);
    }

    /**
     * 修改维修任务
     * 
     * @param busRepair 维修任务
     * @return 结果
     */
    @Override
    public int updateBusRepair(BusRepair busRepair)
    {
        busRepair.setUpdateUser(SecurityUtils.getUserId());
        busRepair.setUpdateBy(SecurityUtils.getUsername());
        busRepair.setUpdateTime(DateUtils.getNowDate());
        return busRepairMapper.updateBusRepair(busRepair);
    }

    /**
     * 批量删除维修任务
     * 
     * @param ids 需要删除的维修任务主键
     * @return 结果
     */
    @Override
    public int deleteBusRepairByIds(Long[] ids)
    {
        return busRepairMapper.deleteBusRepairByIds(ids);
    }

    /**
     * 删除维修任务信息
     * 
     * @param id 维修任务主键
     * @return 结果
     */
    @Override
    public int deleteBusRepairById(Long id)
    {
        return busRepairMapper.deleteBusRepairById(id);
    }

    @Override
    public Integer getRepairCount() {
        return busRepairMapper.getRepairCount();
    }

    /** 派遣任务
     * @param ids
     * @param taskId
     * @return
     */
    @Override
    public String dispatchTask(Long[] ids, Long taskId) {
//        遍历获取每个员工的id,并且向各自信箱发送消息
        for (Long id : ids) {
//            每个员工的信箱的key
            String key =  "msg:" + id;

            String TaskId = Convert.toStr(taskId);
//            向其信箱发送任务
            //            System.currentTimeMillis()     时间戳
            stringRedisTemplate.opsForZSet().add(key, TaskId, System.currentTimeMillis());

        }
        String msg = "发送派遣消息已成功!";

        return  msg;
    }

    /**
     * 获取信箱中的维修任务
     *
     * @return
     */

    @Override
    public List<BusRepair> getRepairTask() {
//      如果当前用户为管理员
        if (SecurityUtils.hasRole("admin")){
            return  null;
        }
//      获取当前用户的id
        Long userId = SecurityUtils.getUserId();
        //        获取当前用户的key
        String key = "msg:" + userId;
//        判断当前用户是否为员工
        if (SecurityUtils.hasRole("common"))
        {
//        查询当前用户的信箱
            Set<String> tasks = stringRedisTemplate.opsForZSet().reverseRange(key, 0, -1);

//       获取集合中的任务id
            Long[] taskIds = null ;
            List<BusRepair> busRepairs = new ArrayList<>();
            if (tasks != null && !tasks.isEmpty()) {
                for (String task : tasks) {
                    // 处理每个 task
                    System.out.println("处理任务: " + task);
//              查询该任务的详细信息
                    BusRepair busRepair = busRepairMapper.selectBusRepairById(Long.parseLong(task));
                    busRepairs.add(busRepair);
                }
            } else {
                System.out.println("没有找到任何任务");
            }
//       返回任务集合
            return busRepairs;
        }else {
            return null;
        }

    }

    /**
     * @param id 任务编号
     * @return
     */
    @Override
    public String deleteTaskCode(Long id) {

        //      获取当前用户的id
        Long userId = SecurityUtils.getUserId();

//        获取当前用户的key
        String key = "msg:" + userId;
//        查询当前用户的信箱
        Set<String> tasks = stringRedisTemplate.opsForZSet().reverseRange(key, 0, -1);
//        删除当前员工的任务编号
        if (tasks != null && !tasks.isEmpty()) {
            for (String task : tasks) {
//                是否为删除的任务的id
//        检查是否有这个任务
                if (id.equals(Long.parseLong(task))){
                    stringRedisTemplate.opsForZSet().remove(key,task);
                }
                }
            }

        return "删除成功";
    }
    @Override
    public  List<MsgList>  getMsgByAdmin() {
        //      获取当前用户的id
        Long userId = SecurityUtils.getUserId();

//        获取当前用户的key
        String key = "msg:" + userId;
        //          返回redis中的消息
        Set<String> msg = stringRedisTemplate.opsForZSet().range(key, 0, -1);

//       创建集合集合消息
        List<MsgList> msgList = new ArrayList<>();
//       将信息加入集合中
        if (msg != null && !msg.isEmpty()) {
            for (String message : msg) {
                MsgList msgList1 = new MsgList(message);
                msgList.add(msgList1);
            }
        }
//        System.out.println("msgList:");
//        msgList.stream().forEach(System.out::println);
        return   msgList ;
    }

    /**
     * @return
     */
    @Override
    public Long[] getRepairAndCompleted() {
        Map<String, Long> countsMap = busRepairMapper.getRepairAndCompleted();
        return new Long[]{countsMap.get("totalCount"), countsMap.get("completedCount")};
    }
}
